<!--
- File:    确认订单.（买花与积分商城）
-->
<template>
  <div>
    <div class="Web_Box">
      <div class="con_tab" v-show="false">
        <ul class="f-cb">
          <li class="bor-r-ddd" :class="{'cur': type == 0}" @click="switchType(0)">邮寄</li>
          <li :class="{'cur': type == 1}" @click="switchType(1)">自提</li>
        </ul>
      </div>
      <div class="ConfirmationOrder">
        <div class="ConsigneeInfo" v-show="type == 0">
          <div class="add_adree" v-show="addressList.requested && addressList.data.length <= 0" @click="gotoAddAddress">添加收货地址</div>
          <div v-show="addressList.requested && addressList.data.length > 0" @click="selectAddress">
            <p class="text1 f-cb"><span class="name fl">收货人:{{address.true_name}} </span>
              <span class="tel fr">{{address.mob_phone}}</span></p>
            <div class="Address slh2">{{address.area_info}} {{address.address}}</div>
            <i class="iconfont icon-more" style="position: absolute;right: 0.5rem;top: 50%;width: 0.575rem;height: 0.575rem;font-size: 1rem;color: #ad2020;margin-top: -0.375rem;"></i>
          </div>
        </div>
        <div class="ConsigneeInfo" style="background: #fff; margin-bottom: 0.25rem" v-show="type == 1">
          <div class="add_adree" v-show="shopAddressList.requested && shopAddressList.data.length <= 0">当前无线下商店数据，暂不能自提</div>
          <div v-show="shopAddressList.requested && shopAddressList.data.length > 0" @click="selectShopAddress">
            <p class="text1 f-cb">
              <span class="name fl"><span class="cr_f23030 pr5">自提门店</span> {{shopAddress.seller_name}} </span>
              <span class="tel fr">{{shopAddress.telphone}}</span></p>
            <div class="Address slh2">{{shopAddress.area_info}} {{shopAddress.address}}</div>
            <i class="iconfont icon-rightdot"></i></div>
        </div>
        <div class="ShopGoods EditPro hidden bor_b_dcdddd">
          <div class="ProList">
            <!--<div class="oeder_tex">订单号:2362356239521521</div>-->
            <div class="oeder_tex"><i class="iconfont icon-dianpu"></i><span>{{buyInfo.store_name}}</span></div>
            <ul>
              <li v-for="item in buyInfo.alldata">
                <!--<div class="tisb cr_898989" v-show="item.is_voucher == '0'" style="background: #eee">无可用优惠券</div>-->
                <div class="Pic">
                  <img :src="$config.imgsite + $config.goodsImgSrc + item.store_id + '/' + item.goods_image + '_w150'" alt=""/>
                </div>
                <div class="Con">
                  <div class="pl20">
                    <h2 class="" style="min-height: auto;">{{item.goods_name}}
                      <!--&nbsp;&nbsp;<span v-for="attr in item.goods_spec">{{attr.name}} </span>-->
                    </h2>
                    <p class="Attribute" style="font-size: 12px; margin-bottom: 0; height: auto;">
                      <span v-for="attr in item.goods_spec">{{attr.name}} </span></p>
                    <p class="PriceQuantity">
                      <span class="fl cr_f84e37" v-if="buyType != $dictionary.buyType.integral">￥{{item.goods_price | discount(item.groupbuy_rebate)}}</span>
                      <span class="fl cr_f84e37" v-else>{{parseInt(item.goods_price)}}积分</span>
                      <span class="fr cr_282828">×{{item.goods_num}}</span>
                    </p>
                  </div>
                </div>
              </li>
              <li v-if="buyType != $dictionary.buyType.integral">
                <p style="font-size: 14px">合计：<span class="cr_f84e37">￥{{buyInfo.total}} &nbsp;</span><span>(运费:￥{{buyInfo.shipping_fee}})</span>
                </p>
              </li>
              <li v-else>
                <p style="font-size: 14px">合计：<span class="cr_f84e37">{{parseInt(buyInfo.total)}}积分 &nbsp;</span><span>(运费:￥{{buyInfo.shipping_fee}})</span>
                </p>
                <div class="test" style="clear: both; padding: .25rem 0;">您当前有<span class="cr_f23030">{{buyInfo.integral}}</span>积分，再支付<span class=" cr_f23030">{{buyInfo.need_goods_price}}</span>元可兑换
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="OtherInfo">
          <ul>
            <li style="line-height: 25px; padding-top: 10px;" v-if="buyType != $dictionary.buyType.integral">
              <p class="totalb_tis f-cb">优惠券<span class="fr Clip" @click="switchCouponShow(true)"><span class="cr_fd6847 ml10" v-if="selectedCoupon">-￥{{selectedCoupon.voucher_price}}</span><span v-show="!selectedCoupon && canUseCouponNum <= 0" class=" cr_898989">无可用优惠券</span><span v-show="!selectedCoupon && canUseCouponNum > 0">使用</span><i class="iconfont icon-more" style="padding-right: 10px; line-height: 24px;"></i></span>
              </p>
            </li>
            <!--<li v-show="false">-->
            <!--<div class="tit">可使用余额支付 </div>-->
            <!--<div class=" pr50">-->
            <!--<span class="cr_fd6847 ml10">￥{{balanceUsed | toFixed(2)}}</span>-->
            <!--&lt;!&ndash;<span class="ml10">(总余额:￥{{buyInfo.balance}})</span>&ndash;&gt;-->
            <!--</div>-->
            <!--<i v-show="!useBalance" class="iconfont icon-pitch2" @click="switchUseBalance(true)"></i>-->
            <!--<i v-show="useBalance" class="iconfont icon-select" @click="switchUseBalance(false)"></i></li>-->
            <li style="height:55px; line-height:40px;" v-if="!selectedCoupon && buyType != $dictionary.buyType.integral">
              <div class="tit">可用积分抵扣</div>
              <div class=" pr50">
                <span class="cr_fd6847 ml10">-￥{{integralUsed | toFixed(2)}}</span>
                <p class=" f12 cr_898989 tis ">积分最多可抵扣订单总额的{{couponSetting.points_orderrate * 100}}%</p>
              </div>
              <i v-show="!useIntegral" class="iconfont icon-pitch2" style="font-size: 1.2rem; width: auto" @click="switchIntegral(true)"></i>
              <i v-show="useIntegral" class="iconfont icon-pitchon2" style="font-size: 1.2rem; width: auto" @click="switchIntegral(false)"></i>
            </li>
            <li>
              <div class="tit">配送方式</div>
              <div class="fr pr20 f24 cr_000">快递</div>
            <li class="Total" style=" height:80px;"><textarea placeholder="买家留言" v-model="remark"></textarea></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="BottomGd">
      <span class="totals">需支付:<span class="cr_fd6847">￥{{payed | toFixed(2)}}</span></span>
      <button class="but_3 fr bg_45a73a" type="button" @click="submitOrder">提交订单</button>
    </div>
    <!--使用优惠券弹窗-->
    <div class="coupbg" v-show="couponModelShow">
      <div class="PopBg" @click="switchCouponShow(false)"></div>
      <div class="coupon_box" style="z-index: 99; max-height: 10rem; overflow-y: scroll">
        <div v-show="buyInfo.voucher_list && buyInfo.voucher_list.length > 0">
          <p class="f-cb pl20">支持优惠券的订单金额：<span>￥{{buyInfo.voucher_goods_total}}</span>
            <!--<span style="position: absolute; right: 20px; vertical-align: middle">-->
            <!--不使用优惠券-->
            <!--<i v-show="!selectedCoupon" class="iconfont icon-pitchon2" style="display: inline-block; width: 16px; height: 16px;color: #25b45b !important; margin: 0 0 0 5px; vertical-align: top" ></i>-->
            <!--<i v-show="selectedCoupon" class="iconfont icon-pitch2" style="display: inline-block; width: 16px; height: 16px;color: #25b45b !important; margin: 0 0 0 5px; vertical-align: top" @click="selectedCoupon = null"></i>-->
            <!--</span>-->
          </p>

          <div class="couponlist f-cb" style="height: 5rem; background-size: 100% 5rem" :class="{'coupon-selected': (selectedCoupon && coupon.voucher_id == selectedCoupon.voucher_id)}" v-for="coupon in buyInfo.voucher_list" v-show="coupon.voucher_type == $dictionary.couponType.buy">
            <div class="fl">
              <p class="c_class">{{coupon.voucher_title}}</p>
              <p class="c_money" style="font-size: 18px;">￥{{coupon.voucher_price}}<span style="font-size: 13px; margin-left: 5px;">({{coupon.voucher_limit | couponUseTxt}})</span>
              </p>
              <p class="c_time">{{coupon.voucher_start_date | timestampToDate('yyyy.MM.dd')}}-{{coupon.voucher_end_date | timestampToDate('yyyy.MM.dd')}}</p>
              <p class="c_class" style="font-size: 12px; color: #999">类型：{{coupon.voucher_type | couponTypeTxt}}</p>
            </div>
            <div class="fr">
              <div v-if="coupon.is_canUse == '1'" style="color: #fff; line-height: 5rem; font-size: 0.8rem; text-align: center" @click="selectCoupon(coupon)">使用</div>
              <!--<p class="c_price">￥<span>{{coupon.voucher_price}}</span></p>-->
              <!--<div class="Choice" v-if="coupon.is_canUse == '1'">-->
              <!--<i class="iconfont icon-pitchon2" v-if="selectedCoupon && coupon.voucher_id == selectedCoupon.voucher_id"></i>-->
              <!--<i class="iconfont icon-pitch2" v-else></i>-->
              <!--</div>-->
              <div v-else style="color: #fff; line-height: 5rem; text-align: center; font-size: 14px;">
                使用条件不足
              </div>
            </div>
          </div>
        </div>
        <div v-show="!buyInfo.voucher_list || buyInfo.voucher_list.length <= 0" style="margin: 0 auto; margin-top: 5rem; text-align: center">
          当前无可用优惠券~
        </div>
        <div class="c_btn" @click="cancleUseCoupon">不使用优惠券</div>
      </div>
    </div>
    <back-nav></back-nav>
    <mt-datetime-picker
      ref="rentDatePicker"
      v-model="value"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleRentDateChange">
    </mt-datetime-picker>
  </div>
</template>

<script>
  import {mapModules, mapRules} from 'vuet'
  import payPop from '../../components/payPop'
  import {DatetimePicker} from 'mint-ui'

  export default{
    mixins: [
      mapModules({addressList: 'addressList', shopAddressList: 'shopAddressList', couponSetting: 'couponSetting'}),
      mapRules({once: ['addressList', 'shopAddressList', 'couponSetting']})
    ],
    data() {
      return {
        buyType: this.$route.query.buyType,
        type: this.$route.query.type || 0, // 0 邮寄 1 自提
        couponModelShow: false,
        from: '',
        buyInfo: {total: 0, integral: 0, balance: 0, alldata: [], voucher_list: []},
//        selectedCouponList: [], // 选择使用的优惠券id列表
        selectedCoupon: null, //  选择使用的优惠券
        useIntegral: false,
        useBalance: false,
        remark: '', // 备注
        order: {order_id: '', pay_sn: ''}, // 提交成功后，对其赋值
        selectedCartIdList: [], // 要购买的商品的cartId列表
        value: new Date()
      }
    },
    components: {
      'mtDatetimePicker': DatetimePicker
    },
    computed: {
      canUseCouponNum () {
        let num = 0
        for (let i = 0; i < this.buyInfo.voucher_list.length; i++) {
          if (this.buyInfo.voucher_list[i].is_canUse) {
            num++
          }
        }
        return num
      },
      // 抵扣的余额
      balanceUsed () {
        let balanceMony = parseFloat(parseFloat(this.buyInfo.balance).toFixed(2))
        let totalMony = parseFloat(parseFloat(this.buyInfo.total).toFixed(2))
        let remain = totalMony
        if (this.useIntegral) {
          remain = parseFloat((totalMony - this.integralUsed).toFixed(2))
        }
        return balanceMony > remain ? remain : balanceMony
      },
      // 抵扣的积分金额
      integralUsed () {
        let integralMoney = this.buyInfo.integral * this.couponSetting.points_money
        let canIntegralMoney = parseInt(parseFloat(this.buyInfo.total) * this.couponSetting.points_orderrate / this.couponSetting.points_money) * this.couponSetting.points_money // 最多可使用积分抵扣的金额
        return integralMoney > canIntegralMoney ? canIntegralMoney : integralMoney
      },
      // 抵扣后需支付的金额
      payed () {
        if (this.buyType == this.$dictionary.buyType.integral) { // 积分商品，返回还需支付的金额
          return parseFloat(this.buyInfo.need_goods_price) + (this.buyInfo.shipping_fee || 0)
        }
        let remain = parseFloat(this.buyInfo.total) + (this.buyInfo.shipping_fee || 0)
        if (this.useIntegral) {
          remain = remain - this.integralUsed
        }
        if (this.useBalance) {
          remain = remain - this.balanceUsed
        }
        if (this.selectedCoupon) { // 使用了优惠券
          remain = remain - this.selectedCoupon.voucher_price
        }
        if (remain < 0) {
          remain = 0
        }
        return remain
      },
      address () {
        if (this.$route.query.addressId) {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].address_id == this.$route.query.addressId) {
              return this.addressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].is_default === '1') {
              return this.addressList.data[i] // 使用默认地址
            }
          }
          if (this.addressList.data.length > 0) {
            return this.addressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      },
      shopAddress () {
        if (this.$route.query.shopAddressId) {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].address_id == this.$route.query.shopAddressId) {
              return this.shopAddressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].is_default === '1') {
              return this.shopAddressList.data[i] // 使用默认地址
            }
          }
          if (this.shopAddressList.data.length > 0) {
            return this.shopAddressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      }
    },
    created() {
//      if (this.from === 'address-list' || this.from === 'address-add') {  // 选择地址页跳回
//        return
//      }
//      this.getCouponSetting()
      console.log('query', this.$route.query.cart)
      this.selectedCartIdList = this.$route.query.cart.toString().split(',')
      console.log('cartIdList', this.$route.query, this.selectedCartIdList)
      this.getBuyInfo(this.selectedCartIdList)
    },
    watch: {
      selectedCoupon: function (newVal) {
        if (newVal) {
          this.useIntegral = false
        }
      },
      $route () {
        this.type = this.$route.query.type
      }
    },
    methods: {
//      getCouponSetting() {
//        this.$request.getCouponSetting().then(data => {
//          this.couponSetting = data
//        })
//      },
      cancleUseCoupon() {
        this.selectedCoupon = null
        this.switchCouponShow(false)
      },
      switchSelectCoupon(coupon) {
        if (coupon.is_canUse == '0') {
          return
        }
        this.selectedCoupon = coupon
      },
//      switchSelectCoupon(coupon) {
//        if (coupon.is_canUse == '0') {
//          return
//        }
//        let index = this.selectedCouponList.indexOf(coupon.voucher_id)
//        if (index > -1) {
//          this.selectedCouponList.splice(index, 1)
//        } else {
//          this.selectedCouponList.push(coupon.voucher_id)
//        }
//      },
//      isInSelectedCouponList(couponId) {
//        let index = this.selectedCouponList.indexOf(couponId)
//        if (index > -1) {
//          return true
//        } else {
//          return false
//        }
//      },
      switchType(value) {
        this.$router.replace({
          name: 'order-rent-confirm',
          query: {cart: this.$route.query.cart, type: value}
        })
      },
      switchUseBalance(boolValue) {
        this.useBalance = boolValue
      },
      switchIntegral(boolValue) {
        this.useIntegral = boolValue
      },
      switchCouponShow(boolValue) {
        this.couponModelShow = boolValue
      },
      openRentDatePicker() {
        this.$refs.rentDatePicker.open()
      },
      handleRentDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.rentInfoEdit.date = dateStr
        console.log(dateStr)
      },
      gotoAddAddress() {
        this.$router.push({
          name: 'address-add',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      getBuyInfo(idList) {
        this.$request.getBuyInfo(idList, this.address.address_id).then(data => {
          this.buyInfo = data
        })
      },
      selectAddress() {
        this.$router.push({
          name: 'address-list',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      selectShopAddress() {
        this.$router.push({
          name: 'address-shop',
          query: {from: 'order-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      submitOrder() {
        let param = {
          cart_id: this.selectedCartIdList,
          ifcart: 1,
          is_balance: this.useBalance ? 1 : 0,
          is_integral: this.useIntegral ? 1 : 0,
          order_note: this.remark,
          pay_name: 'online',
          self: this.type,
          voucher_id: this.selectedCoupon && this.selectedCoupon.voucher_id
        }
        if (this.type == 0) { // 邮寄
          param.address_id = this.address.address_id
        } else if (this.type == 1) { // 自提
          param.address_id = this.shopAddress.address_id
        }
        if (!param.address_id) {
          this.$toast('请先选择地址')
          return
        }
        this.$request.submitOrder(param).then(data => {
//          this.$toast('提交订单成功')
          this.selectedCartIdList = []
          this.order = data
          if (parseFloat(parseFloat(this.payed).toFixed(2)) - 0 <= 0) { // 通过帐号余额支付，不需要走第三方支付
            let orderType = ''
            if (this.buyType == this.$dictionary.buyType.buy) {
              orderType = '1'
            }
            if (this.buyType == this.$dictionary.buyType.integral) {
              orderType = '4'
            }
            this.$router.replace({name: 'order-success', query: {id: this.order.order_id, type: orderType}})
            return
          }
          let paySn = this.order.pay_sn
          payPop({paySn: paySn, orderId: this.order.order_id}, this.canclePay)
        }).catch(e => {
          this.$toast('订单提交失败:' + e.msg)
        })
      },
      canclePay() {
        if (this.buyType == this.$dictionary.buyType.integral) {
          this.$router.replace({name: 'order-integral-detail', params: {id: this.order.order_id}})
        } else {
          this.$router.replace({name: 'order-detail', params: {id: this.order.order_id}})
        }
      },
      selectCoupon(coupon) {
        this.selectedCoupon = coupon
        this.switchCouponShow(false)
      }
    }
  }
</script>

<style>
  .coupon-selected{
    border: 1px solid #3fbc6e;
  }
  .coupon_box .icon-pitchon2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: white !important;
    font-size: 20px;
  }

  .coupon_box .icon-pitch2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: #aaa;
    font-size: 24px;
  }
</style>
